<script setup lang="ts">
import { ElButton, ElInput, Sort, ElDialog, ElMessage, ElTable, ElTableColumn } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'
import { Table } from '@/components/Table'
import {
  getRoomFloorsListApi,
  delRoomFloorsListApi,
  bulkCreateRoomFloorsApi
} from '@/api/room-floor'
import { useTable } from '@/hooks/web/useTable'
import { useUpload } from '@/hooks/web/useUploadExcel'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { TableColumn } from '@/types/table'
import { Search, SearchItem } from '@/components/Search'
import { RoomFloor } from '@/api/room-floor/types'
import { boolean2string } from '@/utils/index'
import { UploadExcel } from '@/components/UploadExcel'
import { get } from 'lodash-es'

defineOptions({
  name: 'RoomFloor'
})

const delLoading = ref(false)

const { push } = useRouter()

const conditions = reactive({
  code: '',
  name: ''
})

const defaultSort = ref<Sort>({
  prop: 'sequence',
  order: 'ascending'
})

const { register, tableObject, methods } = useTable<RoomFloor>({
  getListApi: getRoomFloorsListApi,
  delListApi: delRoomFloorsListApi,
  defaultSort: defaultSort.value
})

const { getList, setSearchParams, onSortChanged } = methods

setSearchParams(conditions)

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'code',
    label: '代码',
    width: '200px',
    sortable: 'custom'
  },
  {
    field: 'name',
    label: '描述',
    width: 'auto',
    showOverflowTooltip: true
  },
  {
    field: 'disabled',
    label: '禁用',
    width: '100px',
    align: 'center',
    headerAlign: 'center',
    formatter: (row: RoomFloor) => {
      return boolean2string(row.disabled)
    }
  },
  {
    field: 'sequence',
    label: '序号',
    width: '100px',
    align: 'right',
    headerAlign: 'right',
    sortable: 'custom'
  },
  {
    field: 'action',
    width: '120px',
    label: '操作',
    headerAlign: 'center',
    align: 'center'
  }
])

const AddAction = () => {
  push('/settings/room-floor-add')
}

const EditAction = (row: RoomFloor) => {
  push(`/settings/room-floor-edit/id/${row.id}`)
}

const delData = async (row: RoomFloor) => {
  tableObject.currentRow = row
  const { delList } = methods
  delLoading.value = true
  await delList([tableObject.currentRow?.id as string], false).finally(() => {
    delLoading.value = false
  })
}

const validExcel = () => {
  return (
    tableHeader &&
    tableHeader[0] === '楼层代码' &&
    tableHeader[1] === '楼层描述' &&
    tableHeader[2] === '是否禁用' &&
    tableHeader[3] === '显示序号'
  )
}

const {
  tableHeader,
  tableData,
  uploadVisible,
  uploadAction,
  closeUpload,
  beforeUpload,
  handleSuccess
} = useUpload()

const uploadData = async () => {
  if (validExcel()) {
    await bulkCreateRoomFloorsApi(
      tableData.map((row) => {
        return new RoomFloor({
          code: get(row, '楼层代码'),
          name: get(row, '楼层描述'),
          disabled: get(row, '是否禁用') === 'Y' ? true : false,
          sequence: get(row, '显示序号', 1)
        })
      })
    )

    closeUpload()
    getList()
  } else {
    ElMessage.error('模板文件不匹配')
  }
}
</script>

<template>
  <Search :model="conditions" @search="setSearchParams" @reset="setSearchParams">
    <SearchItem label="代码" prop="code">
      <ElInput v-model="conditions.code" maxlength="50" clearable />
    </SearchItem>
    <SearchItem label="名称" prop="name">
      <ElInput v-model="conditions.name" maxlength="200" clearable />
    </SearchItem>
  </Search>

  <div class="mt-10px bg-white p-20px">
    <div class="mb-10px flex flex-row justify-between">
      <div>列表</div>
      <div class="flex flex-row items-center">
        <ElButton
          v-hasPermi="'settings:room-floor:add'"
          :icon="Plus"
          type="primary"
          @click="AddAction"
        >
          新建
        </ElButton>
        <ElButton
          v-hasPermi="'settings:room-floor:add'"
          :icon="Upload"
          type="primary"
          @click="uploadAction"
        >
          上传
        </ElButton>
        <Icon icon="ep:refresh-right" class="mr-8px ml-8px cursor-pointer" />
      </div>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      :selection="false"
      :default-sort="defaultSort"
      @register="register"
      @sort-change="onSortChanged"
    >
      <template #action="{ row }">
        <ElButton
          v-hasPermi="'settings:room-floor:edit'"
          type="primary"
          link
          size="small"
          @click="EditAction(row)"
        >
          编辑
        </ElButton>
        <ElButton
          v-hasPermi="'settings:room-floor:remove'"
          type="danger"
          link
          size="small"
          @click="delData(row)"
        >
          删除
        </ElButton>
      </template>
    </Table>
  </div>

  <ElDialog v-model="uploadVisible" fullscreen>
    <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
    <ElTable :data="tableData" border highlight-current-row style="width: 100%; margin-top: 20px">
      <ElTableColumn v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </ElTable>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeUpload">关闭</el-button>
        <el-button type="primary" @click="uploadData"> 保存 </el-button>
      </div>
    </template>
  </ElDialog>
</template>
